import { DownloadOutlined, FileExcelTwoTone, FilePdfTwoTone, FilePptTwoTone, FileTwoTone, FileWordTwoTone } from "@ant-design/icons";
import { Button, Image, Input, Modal, Select, Space } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";
import alert from "../utils/alert";
import client from '../utils/client';
import { isImage } from '../utils/ext';
import FillTable from "./FillTable";
import FillTabs from "./FillTabs";
import Iframe from "./Iframe";
import PDFViewer from "./PdfViewer";
import useModal from "./useModal";

function Attachments({ card, id, groups }) {
  const [data, setData] = useState([]);
  const [selected, setSelected] = useState(null);
  const [modal, modalHolder] = useModal();

  const data_groups = useMemo(() => {
    return [...new Set(data.map(d => d.分组名))]
  }, [data]);

  const reload = useCallback(() => {
    client.job('CardR', {
      Card: 'B.卡片附件',
      Filter: [['卡片名称', '=', card], ['记录ID', '=', id]],
      Order: { '序号': 'asc' }
    }).then(({ Rows }) => {
      setData(Rows);
      if (selected) setSelected(Rows.find(r => r.ID === selected.ID));
    });
  }, [card, id, selected]);

  const upload = useCallback(() => {
    let group;
    Modal.confirm({
      title: `请指定分组`,
      centered: true,
      content: (
        <div style={{ padding: '10px 0' }}>
          {groups ? (
            <Select allowClear style={{ width: '100%' }} onChange={v => group = v}
              options={groups.map(group => ({ value: group, label: group }))} />
          ) : (
            <Input placeholder="请输入分组名称" onChange={e => group = e.target.value} />
          )}
        </div>
      ),
      onOk: () => {
        let file_names = [];
        client.doc.upload_files(`卡片附件/${card}/${id}`, { multiple: true }, (files) => {
          file_names = files.map(file => file.name);
          return !files.some(file => {
            if (file.size > 10 * 1024 * 1024) {
              alert("所选文件超出10MB的大小限制");
              return true;
            }
            return false;
          });
        }).then((paths) => {
          // 保存到卡片附件
          client.job('CardW', {
            Card: 'B.卡片附件',
            Records: paths.map((path, index) => ({
              卡片名称: card,
              记录ID: id,
              文件名: file_names[index],
              扩展名: file_names[index].split('.').pop(),
              存储路径: path,
              分组名: group,
              序号: Date.now() + index,
            })),
          }).then(() => reload());
        });
      }
    });
  }, [card, id, groups, reload]);

  const remove = useCallback(() => {
    client.job('CardD', {
      Card: 'B.卡片附件',
      Record: selected,
    }).then(() => reload());
  }, [selected, reload]);

  const moveUp = useCallback(() => {
    const rows = data.filter(d => d.分组名 === selected.分组名);
    const index = rows.findIndex(r => r === selected);
    if (index > 0) {
      // 交换序号
      const target = rows[index - 1];
      const v = target.序号;
      target.序号 = selected.序号;
      selected.序号 = v;
      client.job('CardW', {
        Card: 'B.卡片附件',
        Model: ['序号'],
        Records: [target, selected]
      }).then(() => reload());
    }
  }, [data, selected, reload]);

  const moveDown = useCallback(() => {
    const rows = data.filter(d => d.分组名 === selected.分组名);
    const index = rows.findIndex(r => r === selected);
    if (index < rows.length - 1) {
      // 交换序号
      const target = rows[index + 1];
      const v = target.序号;
      target.序号 = selected.序号;
      selected.序号 = v;
      client.job('CardW', {
        Card: 'B.卡片附件',
        Model: ['序号'],
        Records: [target, selected]
      }).then(() => reload());
    }
  }, [data, selected, reload]);

  const onPreview = useCallback((e, ext, src) => {
    e.stopPropagation();
    if (['PDF'].includes(ext.toUpperCase())) {
      const mobile = <PDFViewer url={src} />;
      const pc = <Iframe title={src} src={src} />;
      modal.open({
        width: '90%',
        bodyStyle: { height: 'calc(100vh - 60px)' },
        content: navigator.userAgent.includes('Mobile') ? mobile : pc,
        footer: null,
      });
    } else {
      if (Attachments.onPreview) Attachments.onPreview(modal, ext, src);
      else alert("暂不支持该文件格式的在线预览");
    }
  }, [modal]);

  const onDownload = useCallback((e, record) => {
    e.stopPropagation();
    client.doc.download(record.存储路径, record.文件名);
  }, []);

  useEffect(() => {
    reload();
    // eslint-disable-next-line
  }, []);

  return (
    <div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 8, height: '100%', boxSizing: 'border-box' }}>
      <div>
        <Space>
          <Button onClick={reload}>刷新</Button>
          <Button type="primary" onClick={upload}>上传</Button>
          <Button danger disabled={!selected} onClick={remove}>删除</Button>
          <Button disabled={!selected} onClick={moveUp}>上移</Button>
          <Button disabled={!selected} onClick={moveDown}>下移</Button>
        </Space>
      </div>
      <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>
        <FillTabs type="card" onChange={() => setSelected(null)} items={data_groups.map((group, index) => {
          const rows = data.filter(d => d.分组名 === group);
          return {
            key: index,
            label: group || '未指定分组',
            closable: false,
            children: <FillTable pagination={false} style={{ minHeight: 100 }} dataSource={rows}
              columns={[{
                width: 40,
                align: 'center',
                render: (_, record) => {
                  const src = `/api/doc?file=${encodeURIComponent(record.存储路径)}&access_token=${client.get('TOKEN')}`;
                  let comp;
                  if (isImage(record.扩展名)) {
                    comp = <Image alt="image" src={src} />;
                  } else {
                    const props = {
                      style: { fontSize: 18 },
                      onClick: e => onPreview(e, record.扩展名, src),
                    }
                    switch (record.扩展名.toUpperCase()) {
                      case 'PDF':
                        return <FilePdfTwoTone {...props} />;
                      case 'XLS':
                      case 'XLSX':
                        return <FileExcelTwoTone  {...props} />;
                      case 'DOC':
                      case 'DOCX':
                        return <FileWordTwoTone  {...props} />;
                      case 'PPT':
                      case 'PPTX':
                        return <FilePptTwoTone  {...props} />;
                      default:
                        return <FileTwoTone  {...props} />;
                    }
                  }
                  return comp;
                }
              }, {
                title: '文件名',
                dataIndex: '文件名',
                ellipsis: true,
              }, {
                title: '更新时间',
                dataIndex: '更新时间',
                width: 150,
                render: value => value.format('YYYY-MM-DD HH:mm:ss')
              }, {
                width: 30,
                render: (_, record) => {
                  return <DownloadOutlined onClick={e => onDownload(e, record)} />;
                }
              }]}
              rowSelection={{
                hideSelectAll: true,
                selectedRowKeys: selected ? [selected.ID] : [],
                onSelect: (record, selected) => setSelected(selected ? record : null),
              }}
              onRow={(record) => ({
                onClick: () => setSelected(record),
              })} />
          };
        })} />
      </div>
      {modalHolder}
    </div>
  );
}

export default Attachments;